/**
 * @description DOM 编辑器,PageEditorBar中选择dom后，点击进行编辑
 */
Rsd.define('Rsd.tool.DomEditor', {
    extend: 'Rsd.container.Dialog',
    requires: [
        'Rsd.widget.JsonForm',
        'Rsd.tool.DomStyleEditor',
        'Rsd.tool.LinkSelector',
        'Rsd.tool.ProductSelector',
        'Rsd.tool.PromotionCodeSelector',
        'Rsd.hermit.sections.SvgContentPart' 
    ],
    xtype: 'dom-editor',
    readonly: false, 
    autoLoad:false,
    layout: 'vbox',
    width: '80%',
    height: '90%',
    items: [
        {
            name:'json_form_in_dom_editor',
            xtype: 'json-form',
            header: false,
            readonly: false,
            fieldWidth: '90%',
            width: '100%',
            margin: '70 0 10 0', 
            getEditButtonsHandler:'getSchemaButtons',
            formEventHandler:'formEventHandler',
            flex: 1
        },
        {
            id:'dom_editor_top_bar',
            xtype: 'container',
            header: false,
            width: '100%',
            height: 60,
            layout: {type:'hbox',align:'left'},
            style: {
                position: 'absolute',
                top: 50,
                backgroundColor: '#f2f4f0d1'
            },
            items: []
        }
    ],  
    /**
     * 要修改的目标dom
     */
    targetDom: null,
    /**
     * dom 结构体
     */
    domStruct:null,
    //fieldWidth:'33%',
    /**
     * 编辑模式：
     *          {text:"RedJs页面",value:'redjs_hermit'},
                {text:"RedJs模板页",value:'redjs_tpl'},
                {text:"Dom",value:'html_dom'}
     */
    mode:'redjs_hermit',
    /**
     * 当前编辑页面的redjs app对象
     */
    pageApp:null,
    /*
     * */
    constructor: function DomEditor(config) {

        config = config || {};
        this.apply(config);
    },
    /**
     *
     * */
    load: function load() {
 
        this.callParent();
        
        var me = this;
        if(me.items.length ==0)
        {
             console.error('DomEditor item is empty');
             return;
        }
        
        //html_dom 编辑模式 ,动态构建 schema 和 data 
        var _dom_struct = function (dom, dataIndex) {

            //html_dom 编辑模式，动态构建schema
            var dom_editable = dom.getAttribute('dom-editable');
            if(dom_editable==='false')
            {
                return null;
            }

            //console.log(dataIndex,dom.tagName||'textContent',dom.childNodes.length); 

            var schema = {

                "$id": dataIndex,
                "tagName": dom.tagName||'textContent',
                "title": "<span style=\"color:red;\">&lt;" + (dom.tagName||'textContent') + "&gt;</span>&nbsp;" ,
                "dataIndex": dataIndex || dom.name || dom.id,
                "type": "object",
                "properties": [],
                "buttons":me.getDomEditModeButtons()
            };
             
            var data = {};

            var _struct = {
                name: dataIndex,
                "dom":dom,
                schema: schema,
                data: data,
                parent: null,
                items: {}
            };
  
            var parentTagName = dom.parentNode.tagName.toLowerCase(); 
            //表单 头部处理
            //列表 子元素 可以增、删、改
            if ( (parentTagName == 'ul' || parentTagName == 'ol')  && dom.tagName.toLowerCase()=='li') {
                //jsonform中 支持array 对象操作  
            }
            else
            {
                if(dom.outerText)
                {
                    if(dom.outerText.length > 15)
                    {
                        schema.title += ( '{'+ dom.outerText.substring(0,15)+'...}');
                    }
                    else
                    {
                        schema.title += ( '{' + dom.outerText + '}');
                    } 
                }
                
            }
             
            //dom 私有属性处理
            switch (dom.tagName.toLowerCase()) {
                case "label": 
                case "h1":
                case "h2":
                case "h3":
                case "h4":
                case "h5":
                case "h6": 
                {
                    break;
                }
                case "p":
                    {
                        schema.properties.push(
                        {
                            "$id": "innerHTML",
                            "dataIndex": "innerHTML",
                            "label":{
                                content:'HTML',
                                position:'top',
                                style: {textAlign:'left'}
                            }, 
                            "type": "textarea",
                            "onblur":"btn_ok",
                            "height":300
                        });
                        data["innerHTML"] = dom["innerHTML"].trim();
                        break;
                    }
                case "img":
                    {
                        schema.properties.push(
                            {
                                "$id": "src",
                                "dataIndex": "src",
                                "title": '图片地址',
                                "onblur":"btn_ok",
                                "type": "string"
                            });
                        data["src"] = dom["src"];
                        break;
                    }
                case 'svg':
                    {
                        //不支持修改
                        break;
                    }
                case "a":
                    {
                        schema.properties.push({
                            "$id": "href",
                            "dataIndex": "href",
                            "title": '跳转链接',
                            "type": "string",
                            "onblur":"btn_ok",
                            "examples": []
                        });
                        data["href"] = dom["href"];

                        break;
                    }
                case "table":
                    {
                        //表格
                        //schema.type = 'array';
                        console.log(Rsd.select(this, 'tr'));
                        alert('this is table');
                        break;
                    }
                case "form":
                    {
                        //表单  
                        schema.properties.push({
                            "$id": "action",
                            "title": '提交地址',
                            "type": "string",
                            "onblur":"btn_ok",
                            "examples": []
                        });

                        break;
                    }
                case "ul":
                case "ol":
                    {  
                        break;
                    }
                case "li": 
                case "div":
                default:
                    {
                        console.log('通用dom处理:' + dom.tagName );
                        break;
                    }
            }
 
            var list = dom.childNodes;  

            //子dom 处理 
            //文字节点 处理
            //console.log('dom is text',Rsd.isType(dom, Text));
            //当前dom 只有一个子dom 且是文字dom
            if ((list.length == 1 && Rsd.isType(list[0], Text)) 
                || Rsd.isType(dom, Text)) {
 
                //console.log(dom.textContent);
                schema.properties.push({
                    "$id": "innerHTML",
                    "dataIndex": "innerHTML",
                    "title": '文字内容',
                    "onblur": "btn_ok",
                    "type": dom.parentNode.tagName == 'P' ? "textarea" : "string",
                    "height": dom.parentNode.tagName == 'P' ? 60 : 30,
                    "examples": []
                });

                data["innerHTML"] = dom["textContent"].trim();

                return _struct;
            }


            var idx = 0;
            list.forEach(element => {

                //console.log('子元素',element.tagName);

                if(Rsd.isType(element, Text))
                {
                    //子节点中 包含多个节点时，文字节点 不可编辑；但可以通过编辑父节点html实现修改 
                    console.log('子节点中不可编辑文本内容');
                    return;
                }

                if ( Rsd.isType(element, Element) || Rsd.isType(element, Node)) {
                    
                    if (element.getAttribute) {
                        var dom_editable = element.getAttribute('dom-editable');
                        //不可编辑元素
                        if (dom_editable === "false") {
                            console.log('节点标记为不可编辑');
                            return;
                        }
                    }

                    if ((element.tagName && element.tagName.toLowerCase() == 'br')) {
                        return;
                    }

                    idx++;
                    var _d_idx = dataIndex + "_" + (element.tagName || 'text') + "_" + idx;

                    var _item_struct = _dom_struct(element, _d_idx);
                    if(_item_struct==null)
                    {
                        return;
                    }
                    //
                    _item_struct.parent = _struct;
                    _struct.items[_item_struct.name] = _item_struct;

                    schema.properties.push(_item_struct.schema);
                    data[_d_idx] = _item_struct.data;

                    return;
                }

                console.log('unknown element', element);
            });
             
            //只有 一个子dom 
            if (_struct.items.length == 1
                && _struct.schema.properties.length == 1) {

                _struct.items[0].name = _struct.name;
                _struct.items[0].schema.dataIndex = _struct.schema.dataIndex;
                return _struct.items[0];
            }

            return _struct;
        };

        var _title = "";
       
        //schema 分为 已定义schema 和 动态构建schema(不是模板页面，未提前定义)
        //redjs hermit套件模式
        if (me.mode == 'redjs_hermit') {
            
            //console.log('获取 hermit part schema');

            //获取dom 对应的redjs 对象， 
            var item = me.getCurrentItem();

            if(!item.schema)
            {
                var msg = 'dom (id:' + item.id + ') no schema';
                me.title = msg;
                Rsd.msg(msg);
                console.error(msg,item);
                return;
            }
            //me.log('item (id:'+item.id+') schema',item.schema); 
            _title = '&nbsp;&nbsp;['+(item.editInMaster?'母版':'页面')+']&nbsp;&nbsp;' + (item.schema && item.schema.title) + '&nbsp;{'+ item.xtype + '}&nbsp;';
            //获取 对象 schema  
            item.schema.buttons=[
                me.getUpToParentButton(),
                me.getSetStyleButton('_root_',item.schema),
                me.getSettingButton('_root_',item.schema),
                {xtype:'component-x',flex:1},
                me.getDeleteButton()
            ];
            //console.log('this is page item',item);
            var _v_data = item.schema.getViewData(item,"");
            me.domStruct = { 
                schema: item.schema, 
                viewData:_v_data, 
                data: item.schema.getData(item) 
            };
        } 
        //redjs tpl 模板模式
        if (me.mode == 'redjs_tpl') {
            //获取dom 对应的redjs tpl 
            me.targetDom.getAttribute('rsd-tpl');
            //获取 tpl schema
            _title = "";
            console.log('获取 redjs tpl schema');
            me.domStruct = { schema: {}, data: {} };
        }
        //html dom 模式 ：动态构建 schema 和 data 
        if(me.mode == 'html_dom')
        {
            var dom = me.targetDom;
            //console.log(dom.parentNode);
            if (dom.parentNode
                && dom.parentNode.childNodes.length > 1
                && dom.parentNode.tagName.toLowerCase() == "a") {
                dom = dom.parentNode;
            }
            _title = '&nbsp;&nbsp;&lt;' + (dom.name || dom.$id|| dom.tagName) + '&gt;-节点内容编辑';
            me.domStruct = _dom_struct(dom, "_root" + "_" + dom.tagName);
        }
 
        //console.log('dom struct',me.domStruct);
        var _origin_data = me.domStruct.data;
        var _viewData = me.domStruct.viewData;
        var _schema = me.domStruct.schema;
        
        //console.log('schema is', _schema);
        //console.log('origin data is ', _origin_data);
        //console.log('items is',me.items);
        me.title = _title;
        //原始数据，编辑器返回的数据，不会直接应用到控件上；编辑器修改数据后的数据，对该数据进行覆盖；
        me.originData = _origin_data;
        me.forSchema = _schema;

        me.items[0].dataIndex = _schema.dataIndex || _schema.dataindex || _schema.name || _schema.$id || '';
        //加载控件
        me.items[0].removeAll();
        me.items[0].loadFields(_schema);
        //
        if(me.forSchema.for)
        {
            _viewData = _origin_data[me.forSchema.for];
        }
        console.log('dom editor load control (id:'+_origin_data.id+ ') view data{viewData,data}',_viewData,_origin_data);
        
        me.items[0].loadData(_viewData);
        //set buttons 
        me.items[1].removeAll();
        for(var i in _schema.buttons)
        {
            me.items[1].add(_schema.buttons[i]);
        } 
        me.items[1].doLayout();
    },
    /**
     * 获取 当前编辑页面对象
     * @returns 
     */
    getCurrentPage:function getCurrentPage()
    {
        return this.pageApp.currentPage;
    },
    /**
     * @description 获取dom 对应的redjs 对象，
     * @returns 
     */
    getCurrentItem:function getCurrentItem()
    { 
        if(this.mode == 'html_dom')
        {
            console.error('在html_dom模式下无法使用getCurrentItem方法');
            return null;
        }
        if(!this.targetDom)
        {
            console.error('未设置targetDom属性');
            return null;
        }

        var _id = this.targetDom.id;
        if (_id.endWith('_body') || _id.endWith('_ctrl')) {
            _id = _id.substring(0, _id.length - 5);
        }
        //
        var page = this.getCurrentPage();
        return page && page.getItemById(_id);
    },
    /**
     * 
     * @param {*} id 
     * @returns 
     */
    getItemById:function getItemById(id)
    {
        if(this.mode == 'html_dom')
        {
            console.error('在html_dom模式下无法使用getItemById方法');
            return null;
        }
        var page = this.getCurrentPage();
        return page && page.getItemById(id);
    },
    /**
     * 
     * @param {*} evtName 事件名称
     * @param {*} data 编辑器返回的实时数据，一个JsonForm表单数据 
     * @param {*} dataIndex 发生变化的属性，
     * @param {*} sender 事件的发起者
     * @param {*} evt 
     * @param {*} config sender 配置信息
     */
    formEventHandler:function formEventHandler(evtName,data,dataIndex,sender,evt,config)
    {
        console.log('dom editor => formEventHandler(evtName,data,dataIndex,sender,evt,config)',arguments);
        
        var _schema = this.forSchema;
        var _owner = this.forSchema.owner;

        //根据编辑器返回数据，对orginData数据进行 修改 
        var _origin_data = this.originData;  

        //检查schema 是否定义dataIndex关联的属性 
        var _di_arr = dataIndex.split('.');  
        var _ps = _schema.properties;
        
        var _forTpl = sender.parent.forTpl;

        //有两种编辑模式：
        //1、根据schema的viewTemplate生成表单，
        //   只返回控件对应属性，没有层级，需要通过控件向上寻找dataIndex,构建出层级，格式如：aaa.bbb.cc 
       
        //2、根据schema自动生成JsonForm表单
        //   通过dataIndex定位编辑数据的原始位置，格式必须是：aaa.bbb.cc 
        
        //编辑模式1
        if(_forTpl)
        {  
            //没有 dataIndex 对应的属性 ，通过Schema模板编辑
            var parent = sender.parent;
            while(!parent.dataIndex)
            {
                parent = parent.parent;
            }
            if(parent)
            { 
                //list or grid
                var _property_data = _origin_data[parent.dataIndex];
                var _key = data[parent.itemKeyMember];
                var _item = _property_data.find(function (p) {
                    return p[parent.itemKeyMember] === _key;
                });
                if(_item)
                {
                    _item = Rsd.apply(_item, data); 
                }
                console.log(_owner,_item,data,_key,parent.itemKeyMember);

                var _proto = _owner;
                var _is_control = false;
                var _is_container = false;
                //不同 window 下，对象类型相互隔离
                while(_proto && _proto.$className && _is_control == false && _is_container == false)
                {
                    _is_control = _proto.$className == 'Rsd.control.Component';
                    _is_container = _proto.$className == 'Rsd.container.Component';
                    _proto = _proto.__proto__;
                }
                if(_is_container)
                {  
                    _owner = _owner.findItemById(_key);  
                    _owner.loadData(_item);
                    return;
                } 
                //console.log('_owner is control',Rsd.getType(_owner),_owner.__proto__);
                if(_is_control)
                { 
                    _owner.loadData(_property_data);

                    return;
                }

            }
            console.error('schema not contains property:',dataIndex,_schema,_owner,_origin_data,data);
            return;
        }
 
        //编辑模式2

        var _is_changed = false;
        //console.log('sender key is',sender.key);
        //console.log('event name:' + evtName,'is orgin:'+ (this.originData == _origin_data),this.originData,data);
        switch(evtName)
        {
            case "afterItemDown":
                {

                    var list = this._getObjcetData(_origin_data,dataIndex);
                    if(Rsd.isArray(list))
                    {  
                        var index = list.findIndex((p)=>p.id == sender.key || p.key == sender.key); 
                        if(index < 0)
                        {
                            console.error("未找到数组元素:" + sender.key);
                            break;
                        }
                        if(index < (list.length -1))
                        {
                            [list[index + 1], list[index]] = [list[index], list[index + 1]];  
                            _is_changed = true;
                        }
                        else
                        {
                            console.log('已是最后一个');
                        }
                        
                    } 
                    break;
                }
            case "afterItemUp":
                {

                    var list = this._getObjcetData(_origin_data,dataIndex);
                    if(Rsd.isArray(list))
                    {
                        var index = list.findIndex((p)=>p.id == sender.key || p.key == sender.key); 
                        if(index < 0)
                        {
                            console.error("未找到数组元素:" + sender.key);
                            break;
                        }
                        if(index > 0)
                        {
                            [list[index - 1], list[index]] = [list[index], list[index - 1]];
                             _is_changed = true;
                        }
                        else
                        {
                            console.log('已是第一个');
                        }
                    }
                    
                    break;
                }
            case 'afterItemDeleted':
                { 
                    var list = this._getObjcetData(_origin_data,dataIndex);
                    if(Rsd.isArray(list))
                    {
                        var index = list.findIndex((p)=>p.id == sender.key || p.key == sender.key); 
                         if(index < 0)
                         {
                            Rsd.popup('未找到要删除的项目');
                         }
                         else
                         {
                            list.splice(index,1);
                             _is_changed = true;
                            Rsd.popup('项目已删除');
                         }
                    }
                   
                    break;
                }
            case 'itemUpdating':
                {
                    if(this.mode == 'html_dom')
                    {
                        alert('html_dom模式下编辑暂未实现');
                    }
                    else
                    {
                        var item = this.getItemById(sender.key); 
                        if(item)
                        { 
                            this.targetDom = item.dom; 
                            this.items[0].removeAll();
                            this.load();
                        } 
                        else
                        {
                            Rsd.popup('未找到要编辑的项目');
                        }
                    } 
                    break;
                }
            case "fieldValueChange":
                {   
                    //两种编辑事件模式
                    //1、JsonForm 通过JsonSchema 生成的编辑控件 触发
                    //2、JsonForm 通过JsonSchema.ViewTemplate 生成的编辑控件 触发
                    var _new_value = data;
                    if(Rsd.isObject(data))
                    {
                        _new_value = this._getObjcetData(data,_di_arr[_di_arr.length-1]);
                    }
                      
                    //console.log('get field new value from editor ,['+dataIndex+ '] value is ',_new_value,JSON.stringify(data)); 
                    
                    if(this.forSchema.for)
                    {
                        if(!_origin_data[this.forSchema.for])
                        {

                        }
                        this._setObjcetData(_origin_data[this.forSchema.for],dataIndex,_new_value);
                    }
                    else
                    {
                        this._setObjcetData(_origin_data,dataIndex,_new_value);
                    }
                     _is_changed = true;
                    //console.log('after field value change',_origin_data,_schema); 
                    break;
                }
            case "formEvent":    
            default:
                {
                    console.log('json form event handle in dom editor',arguments)
                    break;
                }
                
        }

        if(_is_changed===false)
        {
            return;
        }
       //编辑返回的数据，是页面控件数据的副本，需要赋值给原控件 才会生效
        //console.log('control (id:'+_owner.id+') after updated===》',_origin_data);
        _schema.setData(_owner,_origin_data);
        if(_owner.loadData)
        {
            _owner.loadData();
        } 
        //_origin_data[control.dataIndex].map((p)=>{console.log(p.key)});
    },
    /**
     * 
     * @param {*} obj 
     * @param {*} dataIndex 
     * @returns 
     */
    _getObjcetData:function _getObjcetData(obj,dataIndex)
    {
        var _origin_data = obj;
         if(_origin_data[dataIndex] !== undefined)
         {
            return _origin_data[dataIndex];
         }
        var _di_arr = dataIndex.split('.'); 
        for(var i in _di_arr)
        { 
            //console.log('_getObjcetData',_di_arr[i],_origin_data,obj);
            if(_origin_data[_di_arr[i]])
            { 
                _origin_data = _origin_data[_di_arr[i]]; 
                continue;
            } 
            _origin_data = null;
            break;
        }
        return _origin_data;
    },
   
    /**
     * 
     * @param {*} obj 
     * @param {*} dataIndex 
     * @param {*} value 
     * @returns 
     */
    _setObjcetData:function _setObjcetData(obj,dataIndex,value)
    {
        var _origin_data = obj||{}; 
        var _di_arr = dataIndex.split('.'); 
        for(var i in _di_arr)
        {
            //console.log('_setObjcetData(){index,dataIndex,data,value,is_last}',i,_di_arr[i],_origin_data[_di_arr[i]],value,i == (_di_arr.length -1));
            if(i == (_di_arr.length -1))
            { 
                _origin_data[_di_arr[i]] = value;
                continue;
            }
            if(_origin_data[_di_arr[i]])
            { 
                _origin_data = _origin_data[_di_arr[i]]; 
                continue;
            } 
            _origin_data = null;
            break;
        }
        //console.log('obj data after updated',obj,JSON.stringify(obj));
        return obj;
    },
    /**
     * 
     */
    updateItem:function updateItem(sender,evt,config)
    {
           if(me.itemSchema)
            {
                console.log('has item schema',me.itemSchema,_config);
                _config.formSchema = me.itemSchema;
            }

        //console.log('op col ',_f.items,row);
         //通过配置打开dom编辑窗口 (不应该打开dom 编辑器，应该对接到 外部，由外部决定使用什么编辑器)
         Rsd.create('Rsd.zen.dialog.JsonFormDialog', {
             width: _f.itemWidth || '60%',
             height: _f.itemHeight || 'auto',
             style: { maxHeight: '80%' },
             title: (_f.itemTitle || '子项信息') + '编辑',
             dsName: _f.$id,
             //formSchema: _f.items,
             pageApp: me.pageApp,//当前编辑页面的redjs app对象
             data: row
         }).showDialog();
    },
    /**
     * 
     */
    deleteItem:function deleteItem()
    {

    },
    /**
     * 
     * @returns 
     */
    getDeleteItemButton: function getDeleteItemButton(property,schema) {
        return {
            xtype: 'svg',
             margin: '0 15 0 0',
            dataSource: {
                "viewBox": "0 0 1024 1024",
                path: "M64 960v-68.992h768V960z m448-275.712V339.712h448v344.576z m64-68.928h320v-206.72H576z m-256 68.928V615.36h64v68.928z m-256 0V615.36h64v68.928z m192-68.928V546.432h64v68.928z m-128 0V546.432h64v68.928z m64-68.928V477.504h64v68.928z m64-68.928V408.576h64v68.928z m-128 0V408.576h64v68.928z m192-68.928V339.648h64v68.928z m-256 0V339.648h64v68.928z m0-275.712V64h768v68.928z"
            },
            width: 75,
            height: 40,
            label: {content:'删除项目',position:'right',space:5},
            "tip": "删除选中的项目",
            style: {
                color: 'red',
                float: 'right'
            },
            handlerTarget:'dom',
            handler: function (e) {
                Rsd.popup('删除选中的项目');
            }
        };
    },
    /**
     * 
     * @returns 
     */
    getAddItemButton: function getAddItemButton(property,schema) {
        return {
            xtype: 'svg',
            margin: '0 25 0 0',
            dataSource: {
                "viewBox": "0 0 1024 1024",
                path: "M0.593613 680.416435V341.717925h765.675725v338.69851H0.508811zM41.298491 87.990849C16.875564 96.301428 0.593613 70.860879 0.593613 45.589934c0-25.440549 16.281951-42.400915 40.704878-42.400915h1050.779478c24.422927 0 40.704878 16.960366 40.704879 42.400915 0 25.355747-16.281951 42.231311-40.704879 42.400915H41.298491z m0 932.820132c-24.422927 6.784146-40.704878-18.656403-40.704878-44.096952 0-25.440549 16.281951-42.231311 40.704878-40.704878h1050.779478c24.422927-1.526433 40.704878 15.349131 40.704879 40.78968a41.552897 41.552897 0 0 1-40.704879 44.01215H41.298491z m1001.933624-535.099548v0.084801-144.078309h-48.845854V485.711433h-138.481389v50.881098h138.481389v143.823904h48.845854V536.507729h138.481389v-50.881098h-138.481389z"
            },
            width: 75,
            height: 40, 
            label:{content:'添加项目',position:'right',space:5} ,
            "tip": "添加一个项目",
            style: {
                color: 'green',
                float: 'right'
            },
            handlerTarget:'dom',
            handler: function (e) {
                Rsd.popup('添加一个项目');
            }
        };
    },
    /**
     * 
     */
    getClearItemsButton:function getClearItemsButton(property,schema)
    {
        return {
                    xtype: 'svg',
                    margin: '0 15 0 0', 
                    dataSource: {
                        "viewBox": "0 0 1024 1024",
                        path: "M864 432l48-48 48 48-48 48 48 48-48 48-48-48-48 48-48-48 48-48-48-48 48-48 48 48zM64 448h640v64H64V448z m192-256v64h512V192H256zM128 128h704v192H128V128z m128 576v64h512v-64H256z m-128-64h704v192H128v-192z"
                                
                    },
                    width: 85,
                    height: 40,
                    label:{content:'清除所有',position:'right',space:5} ,
                    "tip": "清除所有项目",
                    style: {
                        color: 'green',
                        float: 'right'
                    },
                    handlerTarget:'dom',
                    handler: function (e) {
                        Rsd.popup('清除所有项目');
                    }
                };
    },
    /**
     * 
     * @returns 
     */
    getSetStyleButton: function getSetStyleButton(property,schema,json_form) {
        
        var me = this;

        return {
            xtype: 'svg',
            margin: '0 15 0 15',
            labelTagName: 'a', 
            width: 52,
            height: 40,
            label: { content: '样式', position: 'right', space: 5 },
            "tip": schema.title + " - 设置样式和动画",
            style: {
                fontSize: '100%',
                cursor: 'pointer',
                textDecoration: 'underline',
                textUnderlineOffset: '5px',
                color: 'blue',
                backgroundColor: 'transparent'
                //float: 'right'
            },
            dataSource: {
                "viewBox": "0 0 1024 1024",
                path: "M789.312 465.92l56 213.12L1024 743.488l-177.92 66.56L792.576 1024l-56-213.12-178.688-64.576 178.048-66.56 53.44-213.76zM848.128 0a130.56 130.56 0 0 1 130.304 124.224l0.192 6.528v529.536l-65.28-21.12V130.816c0-34.432-26.624-62.72-60.352-65.216l-4.864-0.128H130.496a65.28 65.28 0 0 0-65.088 60.48l-0.192 4.864V849.92c0 34.496 26.624 62.72 60.416 65.216l4.864 0.192h562.304l27.84 65.344H130.56a130.56 130.56 0 0 1-130.368-124.16L0 849.92V130.752C0 60.8 54.912 3.584 123.968 0.192L130.496 0h717.632zM415.616 466.56l69.952 141.248 134.4 19.456-115.136 72.256-6.912 157.44-69.76-141.184-134.592-19.456L408.704 624l6.912-157.44z m233.728-106.944l31.296 89.6 78.976 21.504-74.048 34.752-15.68 93.44-31.488-89.6-78.848-21.376 74.24-34.688 15.552-93.632z"
            },
            dataIndex:property,
            propertySchema:schema,
            handlerTarget:'dom',
            handler: function (s,e) {
                 
                //获取dom 对应的redjs 对象， 
                var item = me.getCurrentItem();
                if(me.forSchema.for)
                {
                    item = item[me.forSchema.for];
                }
                if(s.dataIndex && s.dataIndex !== '_root_')
                {
                    item = item[s.dataIndex];
                } 
                //console.log('style is ',item.style,s,e,item);
                Rsd.create('Rsd.tool.DomStyleEditor', {
                    title: s.propertySchema.title + ' - 样式和动画',
                    height:'100%',
                    width:'30%',
                    parent:me,
                    dataIndex:s.dataIndex,
                    data:Rsd.clone(item.style),//防止干扰数据源
                    fieldValueChange:'formEventHandler'
                }).showDialogOnRight();
            }
        };
    },
    /***
    * 
    */
    getEditHtmlButton: function getEditHtmlButton(property,schema,form) {
        var me = this;
        return {
            xtype: 'svg',
            margin: '0 0 0 15',
            dataSource: {
                "viewBox": "0 0 1024 1024",
                path: "M194.336 479.776H93.056v-101.28H47.008v267.04h46.048v-119.712h101.28v119.712h46.048v-267.04H194.336v101.28z m82.88-64.48h73.664v230.208h46.048v-230.208h73.664v-36.832H277.216v36.832z m350.592 145.12l-46.752-181.92h-73.664v267.04h46.048v-211.776l46.048 211.776h55.232l46.816-213.92-0.8 213.92h46.048v-267.04h-73.664l-45.312 181.92z m220.288 48.288v-230.208h-46.048v267.04h174.944v-36.832h-128.896z"
            },
            width: 70,
            height: 40,
            labelTagName: 'a', 
            label: { content: '编辑', position: 'right', space: 5 },
            "tip": "编辑html",
            style: {
                fontSize: '100%',
                cursor: 'pointer',
                textDecoration: 'underline',
                textUnderlineOffset: '5px',
                color: 'blue',
                backgroundColor: 'transparent'
                //float: 'right'
            },
            handlerTarget:'dom',
            handler: function (sender,e) { 
                var _html_form = sender.parent.parent; 
                //获取dom 对应的redjs 对象， 
                var item = me.getCurrentItem();
                var dataIndex = property + '.content'; 
                //var dataSource = item.dataSource;
                var html = me._getObjcetData(item.dataSource,dataIndex);
                //console.log('edit html in control',property,schema,item,html);
                var editor =  Rsd.create('Rsd.tool.RichTextEditor', {
                    contentType:'text/html',
                    title: '编辑HTML',
                    autoLoad:false,
                    height:'60%',
                    width:'60%',
                    tragetItem:item,
                    saveHandler:function(content){
                        
                        _html_form.getFieldControl('content').setValue(content);
                        var _origin_data = me.items[0].getRecord();   
                        me.formEventHandler("fieldValueChange",_origin_data,dataIndex,sender,e);
                        editor.close();
                    }
                });
                editor.showDialog().load(html);
            }
        };
    },
    /**
     * 
     * @param {*} property 
     */
    getInsertDomButton:function getInsertDomButton(property,schema)
    {
         return  {
             xtype: 'svg',
             height: 35,
             width: 95,
             margin: '0 10 0 0',
             labelTagName: 'a',
             label: {
                 content: '插入新节点',
                 position: 'right',
                 space: 5,
                 style: {
                     fontSize: '100%',
                     cursor: 'pointer',
                     textDecoration: 'underline',
                     textUnderlineOffset: '5px',
                     color: 'blue',
                     backgroundColor: 'transparent'
                 }
             },
             tip: '在该节点前插入新节点',
             dataSource: {
                 "viewBox": "0 0 1024 1024",
                 "paths": ["M511.5 957.9C264.9 957.9 65 758.2 65 511.9s199.9-446 446.5-446S958 265.6 958 511.9c0.1 246.3-199.8 446-446.5 446zM509 149.1c-200.4 0-355.8 162.2-355.8 362.3 0 200.1 155.4 356.8 355.8 356.8s362.9-156.7 362.9-356.8c0-200.1-162.5-362.3-362.9-362.3zM690.5 556h-134v133.8c0 24.6-20 44.6-44.6 44.6h-0.1c-24.6 0-44.6-19.9-44.6-44.6V556h-134c-24.7 0-44.6-19.9-44.6-44.5v-0.1c0-24.6 20-44.6 44.6-44.6h134V333c0-24.6 20-44.6 44.6-44.6h0.1c24.7 0 44.6 19.9 44.6 44.6v133.8h134c24.7 0 44.6 19.9 44.6 44.6v0.1c0 24.6-19.9 44.5-44.6 44.5z m0 0"]
             },
             handlerTarget: 'dom',
             handler: function (sender, event) {
                 Rsd.popup('new child node');
             }
         };
    },
    /**
     * 
     */
    getUpToParentButton: function getUpToParentButton() {

        return {
            xtype: 'svg',
            margin: '0 0 0 15',
            labelTagName: 'a',
            height: 40,
            width: 95,
            style: {
                    fontSize: '100%',
                    textAlign: 'left',
                    cursor: 'pointer',
                    textDecoration: 'underline',
                    textUnderlineOffset: '5px',
                    color: 'blue',
                    backgroundColor: 'transparent'
                },
            label: {
                content: '转到父节点',
                position: 'right',
                space: 5, 
            },
            tip: '跳转到该节点的父节点位置',
            dataSource: {
                "viewBox": "0 0 1024 1024",
                "path": "M601.12 419.68H167.68l210.4-208a43.2 43.2 0 0 0 13.92-32 42.72 42.72 0 0 0-13.92-32 41.28 41.28 0 0 0-61.92-0.96L32 425.92a40.96 40.96 0 0 0 0 61.6l284.8 278.4a41.44 41.44 0 0 0 61.92 0 41.12 41.12 0 0 0 0-61.44L167.68 500.8h433.28c173.28 0 324.32 135.04 324.32 302.24v43.2a40.64 40.64 0 1 0 80.96 0v-43.2c0-216.64-182.56-383.2-405.28-383.2z"
            },
            handlerTarget:'dom',
            handler: function (sender, event) {
                        var me = this.parent.parent; 
                        var _target_dom = null;  
                        if (me.targetDom) { 
                            var nodes = me.targetDom.ownerDocument.querySelectorAll('#'+me.targetDom.id); 
                            //console.log(nodes[0].parentNode.parentNode);
                            var _parent = nodes[0].parentNode; 
                            while(_parent)
                            {  
                                if(_parent.getAttribute && _parent.getAttribute("dom-editable")==='true')
                                {
                                    _target_dom = _parent; 
                                    break;
                                }
                                _parent = _parent.parentNode; 
                            } 
                        }
                        if(_target_dom)
                        {
                            me.targetDom = _target_dom;
                            me.items[0].removeAll();
                            me.load();
                        }
                        else
                        {
                            alert('已是最顶层');
                        }
                    } 
        };
    },
    /**
     * 
     * @returns 
     */
    getDeleteButton: function getDeleteButton(property,schema) {

        return {
            xtype: 'svg',
            height: 40,
            width: 95,
             margin: '0 15 0 15',
            labelTagName: 'a',
            style: {
                fontSize: '100%',
                cursor: 'pointer',
                textDecoration: 'underline',
                textUnderlineOffset: '5px',
                color: 'red',
                backgroundColor: 'transparent'
            },
            label: {
                content: '删除该模块',
                position: 'right',
                space: 5,
            },
            tip: '删除当前选中的模块',
            dataSource: {
                "viewBox": "0 0 1024 1024",
                "paths": [
                    "M509.357 128.667c-211.705 0-375.946 171.424-375.946 382.863 0 211.434 164.24 376.969 375.946 376.969 211.75 0 383.401-165.537 383.401-376.969 0-211.439-171.65-382.863-383.401-382.863zM511.998 983.215c-260.586 0-471.818-211.013-471.818-471.218 0-260.251 211.232-471.213 471.818-471.213s471.821 210.96 471.821 471.213c0 260.205-211.235 471.218-471.821 471.218z",
                    "M276.148 512c0-26.052 20.877-47.169 46.953-47.169h377.797c25.932 0 46.953 20.937 46.953 47.169 0 26.052-20.877 47.169-46.953 47.169h-377.797c-25.932 0-46.953-20.937-46.953-47.169z"
                ]
            },
            handlerTarget:'dom',
            handler: function (sender, event) {
                var me = this.parent.parent;
                if (me.mode == 'redjs_hermit') {
                    var item = me.getCurrentItem();
                    item.remove();
                    item.parent.doLayout();
                    me.close();
                    Rsd.popup('the node has removed');
                }
                if (me.mode == 'redjs_tpl') {
                    Rsd.popup(' node  remove 未实现');
                }
                if (me.mode == 'html_dom') {
                    me.targetDom.remove();
                    Rsd.popup('the node has removed');
                } 
            } 
        };
    },
    /**
     * 根据属性名称和schema 获取设置（高级）
     * @returns 
     */
    getSettingButton: function getSettingButton(property,schema,form) {
        var me = this;
        //console.log('getSettingButton',property,schema,form);
        return {
            xtype: 'svg', 
            height: 40,
            width: 63,
            margin: '0 15 0 0',
            labelTagName: 'a',
            style: {
                fontSize: '100%',
                cursor: 'pointer',
                textDecoration: 'underline',
                textUnderlineOffset: '5px',
                color: 'blue',
                backgroundColor: 'transparent'
            },
            label: {
                content: '高级',
                position: 'right',
                space: 5,
            },
            tip: '更多设置',
            dataSource: {
                "viewBox": "0 0 1024 1024",
                "paths": [
                    "M298.666667 315.733333m68.266666 0l85.333334 0q68.266667 0 68.266666 68.266667l0 85.333333q0 68.266667-68.266666 68.266667l-85.333334 0q-68.266667 0-68.266666-68.266667l0-85.333333q0-68.266667 68.266666-68.266667Z",
                    "M298.666667 588.8m68.266666 0l85.333334 0q68.266667 0 68.266666 68.266667l0 85.333333q0 68.266667-68.266666 68.266667l-85.333334 0q-68.266667 0-68.266666-68.266667l0-85.333333q0-68.266667 68.266666-68.266667Z",
                    "M571.733333 588.8m68.266667 0l85.333333 0q68.266667 0 68.266667 68.266667l0 85.333333q0 68.266667-68.266667 68.266667l-85.333333 0q-68.266667 0-68.266667-68.266667l0-85.333333q0-68.266667 68.266667-68.266667Z",
                    "M315.733333 298.666667a34.133333 34.133333 0 0 0-34.133333 34.133333v85.333333a34.133333 34.133333 0 0 0 34.133333 34.133334h85.333334a34.133333 34.133333 0 0 0 34.133333-34.133334V332.8a34.133333 34.133333 0 0 0-34.133333-34.133333H315.733333z m0-34.133334h85.333334a68.266667 68.266667 0 0 1 68.266666 68.266667v85.333333a68.266667 68.266667 0 0 1-68.266666 68.266667H315.733333a68.266667 68.266667 0 0 1-68.266666-68.266667V332.8a68.266667 68.266667 0 0 1 68.266666-68.266667zM315.733333 571.733333a34.133333 34.133333 0 0 0-34.133333 34.133334v85.333333a34.133333 34.133333 0 0 0 34.133333 34.133333h85.333334a34.133333 34.133333 0 0 0 34.133333-34.133333V605.866667a34.133333 34.133333 0 0 0-34.133333-34.133334H315.733333z m0-34.133333h85.333334a68.266667 68.266667 0 0 1 68.266666 68.266667v85.333333a68.266667 68.266667 0 0 1-68.266666 68.266667H315.733333a68.266667 68.266667 0 0 1-68.266666-68.266667V605.866667a68.266667 68.266667 0 0 1 68.266666-68.266667zM588.8 571.733333a34.133333 34.133333 0 0 0-34.133333 34.133334v85.333333a34.133333 34.133333 0 0 0 34.133333 34.133333h85.333333a34.133333 34.133333 0 0 0 34.133334-34.133333V605.866667a34.133333 34.133333 0 0 0-34.133334-34.133334H588.8z m0-34.133333h85.333333a68.266667 68.266667 0 0 1 68.266667 68.266667v85.333333a68.266667 68.266667 0 0 1-68.266667 68.266667H588.8a68.266667 68.266667 0 0 1-68.266667-68.266667V605.866667a68.266667 68.266667 0 0 1 68.266667-68.266667z",
                    "M665.6 252.716575m48.271823 48.271823l60.339779 60.339779q48.271823 48.271823 0 96.543646l-60.339779 60.339779q-48.271823 48.271823-96.543646 0l-60.339779-60.339779q-48.271823-48.271823 0-96.543646l60.339779-60.339779q48.271823-48.271823 96.543646 0Z",
                    "M631.466667 218.583242m48.271823 48.271823l60.339778 60.339779q48.271823 48.271823 0 96.543646l-60.339778 60.339778q-48.271823 48.271823-96.543646 0l-60.339779-60.339778q-48.271823-48.271823 0-96.543646l60.339779-60.339779q48.271823-48.271823 96.543646 0Z"
                ]
            }, 
            handlerTarget:'dom',
            handler: function (sender, event) { 
                 var _form = sender.parent.parent; 
                //console.log(_form,_form.formSchema);

                //获取dom 对应的redjs 对象， 
                var item = me.getCurrentItem();  
                
                 //获取对象schema
                    var filter = [/__/,'$className','dependencies','extend','$id',
                        'dom','domFlagValue','domFlag',
                        'domTagName','bodyTagName','headerTagName','ctrlTagName','labelTagName',
                        'domEditable','editInMaster',
                        'layouter','schema','parent','events','style','modular','from',
                        'timing','isLayout',
                        'element','elements',
                        'items','listeners','handler','fn','itemClick',
                        'liNodes','itemDrag','itemStyle',
                        'isDialog','title',
                        'beforeShow','afterShow','beforeClose','afterClose','beforeInit','afterInit','beforeLayout','afterLayout','beforeRender','afterRender'
                    ];

                    _schema = Rsd.getJsonSchema(item,filter,false);
  
                 //console.log('data and schema',_form.dataIndex,item,_schema);
                 Rsd.create('Rsd.zen.dialog.JsonFormDialog', { 
                        title: 'Redjs控件属性编辑', 
                        width:1000,
                        height:'80%',
                        formSchema:{type:'object',properties:_schema},
                        data: item
                    }).showDialog();

                // Rsd.create('Rsd.tool.PropertiesEditor', {
                //     title: 'Redjs控件属性编辑',
                //     height:'80%'
                // }).showDialog().load(item);
            } 
        };
    }, 
    /**
     * 为已定义 schema 控件 提供 button
     * @param {*} schema 
     * @returns 
     */
    getSchemaButtons:function getSchemaButtons(propertyName,schema,form)
    {
        var btns = [];
        //console.log('get json form buttons {propertyName,schema,form}',propertyName,schema,form)
        switch(schema.type)
        {
            case 'array':
                {
                    btns =  [this.getAddItemButton(propertyName,schema,form),this.getDeleteItemButton(propertyName,schema,form)];
                    break;
                } 
                case 'object':
                 {
                    if(schema.properties['style'] && schema.properties['style'].$ref == 'style')
                    {
                        schema.properties['style'].xtype = 'hidden';
                        btns = [
                            this.getSetStyleButton(propertyName,schema,form), 
                        ]; 
                    }
                    else
                    {
                        btns = [];
                    }
                    if(schema.$ref && schema.$ref == 'html')
                    {
                        btns.splice(0,0,this.getEditHtmlButton(propertyName,schema,form));
                    }
                    break;
                 } 
        }

        return btns;
    }, 
    /**
     * 
     * @returns 
     */
    getDomEditModeButtons: function getDomEditModeButtons(propertyName,schema,form) {
        
        return [
            {
                width: 10,
            },
            this.getUpToParentButton(propertyName,schema,form),
            {
                flex: 1,
            },
            this.getInsertDomButton(propertyName,schema,form),
            this.getDeleteButton(propertyName,schema,form),
            this.getSettingButton(propertyName,schema,form),
            {
                width: 15,
            }
        ];
    },
    /**
     * html_dom 编辑模式
     */
    btn_ok: function btn_ok() {
        //console.log(this);
        var me = this;
        var new_data = me.items[0].getRecord(); 
        //console.log('new data', new_data);
        var _set_data = function(struct,data)
        {
            for (var p in data) {
                if(Rsd.isObject(data[p]))
                { 
                    _set_data(struct.items[p],data[p]); 
                    continue;
                }
                //console.log(p,struct.dom[p]);
                if (struct.dom[p] != data[p]) {
                    struct.dom[p] = data[p];
                }
            }
    
        };
          
        _set_data(me.domStruct,new_data);

        //判断该dom 是否 是在模板中的
        var struct = me.domStruct;  
         //console.log(struct)
        var _dom = struct.dom;
        
        //检查自身和父节点 是否有模板标识 
        var tpl = _dom.getAttribute('rsd-tpl');
        while (!tpl) {
            _dom = _dom.parentNode;
            if (_dom == null || _dom.tagName.toLowerCase() == "body") {
                break;
            }
        }

        if (tpl) {
            //模板中的dom 修改，需要模板文件
            console.error("修改模板文件: " + tpl);
        }
    }

}, function (type) {
  
});
 
